package com.example.weixinsystem.security;

import com.example.weixinsystem.service.SysMenuService;
import com.example.weixinsystem.service.SysUserService;
import com.weixin.common.core.entity.SysUser;
import com.weixin.common.core.exception.BaseException;
import com.weixin.common.core.form.LoginUserDetails;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * @version 1.0.0
 * @className: UserDetailsServiceImpl
 * @description: security 的用户服务
 * @author: zhangjunfa
 * @date: 2023/5/27 13:56
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    private SysUserService sysUserService;
    private SysMenuService sysMenuService;

    public UserDetailsServiceImpl(SysUserService sysUserService, SysMenuService sysMenuService) {
        this.sysUserService = sysUserService;
        this.sysMenuService = sysMenuService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = this.sysUserService.getUserByUsername(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new BaseException("用户名或密码错误");
        }

        // TODO: 2023/5/27 根据用户查询权限信息 添加到LoginUser中
        Set<String> set = this.sysMenuService.getUserPossessMenu(user.getId());
        //封装成UserDetails对象返回
        return new LoginUserDetails(user, set);
    }
}
